/*
 * Copyright (C) 2011 Consulanza Informatica.
 * info@consulanza.it
 *
 * This file is part of Customer Calls Tracker.
 *
 *    Customer Calls Tracker is free software: you can redistribute it and/or
 *    modify it under the terms of the GNU General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or (at 
 *    your option) any later version.
 *
 *    Customer Calls Tracker is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General 
 *    Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with Customer Calls Tracker. If not, see http://www.gnu.org/licenses/.
 *
 * Portions of this software is a derivate work from:
 *
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package consulanza.amlsoft.customercalls;

//import java.text.DateFormat;

import consulanza.amlsoft.customercalls.CustomerCallsDbAdapter.CustomerCall;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class CallEdit extends Activity {
//    private final String TAG = "CustomerCalls CallEdit";
	/*
	 * form fields
	 */
    private EditText mCustomer;
    private EditText mNotes;
    private CheckBox mFlagBilled;
    private CheckBox mFlagCall;
    private TextView mDowStart;
    private TextView mTimeStart;
    private TextView mDowEnd;
    private TextView mTimeEnd;
    private TextView mDisplay_hourstot;
    private Button   btnSelectCustomer;
    private Button   btnSave;
    private Button   btnCancel;
    /*
     * local form buffer 
     */
    private String	fbCustomer;	 // 
    private String	fbTimeStart; // current value stored in iso format
    private String 	fbTimeEnd;	 // current value stored in iso format
    
    private Long mRowId;
    private CustomerCallsDbAdapter mDbHelper;
    
    /*
     * costante 
     */
    private static final int PICK_CONTACT = 1;
	/*
	 * costanti ID dialoghi
	 */
	public static final int DLG_ID_DATETIME = 0;
	/*
	 * 
	 */
	public static final int DLG_INSTANCE_TIMESTART = 0;
	public static final int DLG_INSTANCE_TIMEEND = 1;

	private int mDateTimeDlgInstance;
	
    /**
     * Creazione della finestra di dialogo per l'acquisizione di data e ora
     * @return
     */
	private final Dialog createDateTimeDialog() {

		Context mContext = getApplicationContext();
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		final View layout = inflater.inflate(R.layout.datetime_dialog,
		                               (ViewGroup) findViewById(R.id.dateTimeDialogRoot));		
		
		// Otteniamo il riferimento al Builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Impostiamo il titolo, il messaggio ed una icona in chaining
		builder.setTitle(R.string.label_datetime_dialog);
		builder.setIcon(R.drawable.icon);
		// builder.setMessage(R.string.datetime_dialog_message);
		builder.setView(layout);
		// Set listener for SAVE button
		builder.setPositiveButton(R.string.label_ok,
				new DialogInterface.OnClickListener() {

					//@Override
					public void onClick(DialogInterface dialog, int id) {
						DatePicker datepicker = (DatePicker) layout.findViewById(R.id.DlgDatePicker);
						TimePicker timepicker = (TimePicker) layout.findViewById(R.id.DlgTimePicker);
//						String dateString = String.format("%02d-%02d-%02d %02d:%02d:00", 
						String dateString = String.format("%02d-%02d-%02d %02d:%02d",
														datepicker.getYear(),
														datepicker.getMonth()+1,
														datepicker.getDayOfMonth(),
														timepicker.getCurrentHour(),
														timepicker.getCurrentMinute());
						Toast.makeText(CallEdit.this,dateString, Toast.LENGTH_LONG).show();
						switch (mDateTimeDlgInstance) {
						case DLG_INSTANCE_TIMESTART:
							fbTimeStart = dateString;
							break;
						case DLG_INSTANCE_TIMEEND:
							fbTimeEnd = dateString;
							break;
						}
						updateDisplay();
					}

				});
		// Impostiamo il pulsante di No con il relativo listener
		builder.setNegativeButton(R.string.label_cancel,
				new DialogInterface.OnClickListener() {

					//@Override
					public void onClick(DialogInterface dialog, int id) {
						Toast.makeText(CallEdit.this,
								R.string.label_cancel, Toast.LENGTH_SHORT).show();
					}

				});
		TimePicker timepicker = (TimePicker) layout.findViewById(R.id.DlgTimePicker);
		timepicker.setIs24HourView(DateFormat.is24HourFormat(this));
		// Restituiamo l'Alert creato
		return builder.create();
	}

    /**
     * setup controls events 
     */
    public void setupControlsEvents() {
		/*
		 * link SAVE Button event
		 */
		btnSave.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                setResult(RESULT_OK);
                saveCall();
                finish();
            }
        });
		/*
		 * link CANCEL Button event
		 */
		btnCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
		/*
		 * link SELECT CUSTOMER button click event
		 */
		btnSelectCustomer.setOnClickListener(new OnClickListener() {

			//@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, PICK_CONTACT);
			}
		});
		/*
		 * link START TIME text tap event
		 */
		mTimeStart.setOnTouchListener(new OnTouchListener() {
			//@Override
			public boolean onTouch(View v, MotionEvent event) {
				mDateTimeDlgInstance = DLG_INSTANCE_TIMESTART;
				showDialog(DLG_ID_DATETIME);
				return false;
			}
		});
    	
		/*
		 * link END TIME text tap event
		 */
		mTimeEnd.setOnTouchListener(new OnTouchListener() {
			//@Override
			public boolean onTouch(View v, MotionEvent event) {
				mDateTimeDlgInstance = DLG_INSTANCE_TIMEEND;
				showDialog(DLG_ID_DATETIME);
				return false;
			}
		});
    }
    /**
     * 
     */
    protected void setupEventsListeners() {
    }
    /**
     * 
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new CustomerCallsDbAdapter(this);
        mDbHelper.open();

        setContentView(R.layout.call_edit);
        setTitle(R.string.label_edit_call);

        mCustomer 		= (EditText) findViewById(R.id.edit_customer);
        mFlagCall 		= (CheckBox) findViewById(R.id.check_call);
        mFlagBilled		= (CheckBox) findViewById(R.id.check_billed);
        mNotes 			= (EditText) findViewById(R.id.edit_notes);
        mDowStart 		= (TextView) findViewById(R.id.edit_dowstart);
        mTimeStart 		= (TextView) findViewById(R.id.edit_start);
        mDowEnd 		= (TextView) findViewById(R.id.edit_dowend);
        mTimeEnd  		= (TextView) findViewById(R.id.edit_end);
        mDisplay_hourstot = (TextView) findViewById(R.id.display_hourstot);

        btnSelectCustomer = (Button) findViewById(R.id.button_select_customer);
        btnSave			= (Button) findViewById(R.id.btn_save);
        btnCancel		= (Button) findViewById(R.id.btn_cancel);

        fbCustomer 	= getString(R.string.value_no_customer);
        fbTimeStart	= Util.nowToString(); // inizializza orario
        fbTimeEnd 	= Util.nowToString(); // inizializza orario
        mNotes.setText("");
        mFlagCall.setChecked(true);

        mRowId = (savedInstanceState == null) ? null
        			: (Long) savedInstanceState.getSerializable(CustomerCall.KEY_CUSTOMER);
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = (extras == null) ? null 
						: extras.getLong(CustomerCall.KEY_ROWID);
		}

		setupControlsEvents();
		setupEventsListeners();
		getFbValues();
		
    }
    /**
     * Events handling
     */
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
    	super.onActivityResult(reqCode, resultCode, data);

    	switch (reqCode) {
    	case (PICK_CONTACT):
    		if (resultCode == Activity.RESULT_OK) {
	    			Uri contactData = data.getData();
	    			Cursor c = managedQuery(contactData, null, null, null, null);
	    			if (c.moveToFirst()) {
	    				String customer = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
	    				fbCustomer = customer;
    			}
    		}
    	break;
    	}
    }
    /**
     * carica i valori dal DB
     */
    private void getFbValues() {
        if (mRowId != null) {
            Cursor call = mDbHelper.fetchCall(mRowId);
            startManagingCursor(call);
            fbCustomer 	= call.getString(call.getColumnIndexOrThrow(CustomerCall.KEY_CUSTOMER));
            fbTimeStart = call.getString(call.getColumnIndexOrThrow(CustomerCall.KEY_START));
            fbTimeEnd 	= call.getString(call.getColumnIndexOrThrow(CustomerCall.KEY_END));
            mNotes.setText(call.getString(call.getColumnIndexOrThrow(CustomerCall.KEY_NOTES)));
            mFlagCall.setChecked(Util.int2bool(call.getInt(call.getColumnIndexOrThrow(CustomerCall.KEY_FLAG_CALL))));
            mFlagBilled.setChecked(Util.int2bool(call.getInt(call.getColumnIndexOrThrow(CustomerCall.KEY_FLAG_BILLED))));
        }
    }
    /**
     * aggiorna i campi nella form
     */
    private void updateDisplay() {
    	mCustomer.setText(fbCustomer);
    	mDowStart.setText(Util.dateToDow(Util.dbDateToDate(fbTimeStart)));
    	mTimeStart.setText(Util.dateToString(Util.dbDateToDate(fbTimeStart)));
    	mDowEnd.setText(Util.dateToDow(Util.dbDateToDate(fbTimeEnd)));
        mTimeEnd.setText(Util.dateToString(Util.dbDateToDate(fbTimeEnd)));
        mDisplay_hourstot.setText(Util.timeDiff(fbTimeStart,fbTimeEnd));
    }
    /**
     * salva lo stato
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("fbCustomer",fbCustomer);
        outState.putString("mNotes",mNotes.getText().toString());
        outState.putString("fbTimeStart",fbTimeStart);
        outState.putString("fbTimeEnd",fbTimeEnd);
        outState.putBoolean("mFlagCall",mFlagCall.isChecked());
        outState.putBoolean("mFlagBilled",mFlagBilled.isChecked());
        outState.putSerializable(CustomerCall.KEY_ROWID, mRowId);
        super.onSaveInstanceState(outState);
    }
    /**
     * ripristina lo stato
     */
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	if (savedInstanceState != null) {
	    	fbCustomer 	= savedInstanceState.getString("fbCustomer");
	    	fbTimeStart = savedInstanceState.getString("fbTimeStart");
	    	fbTimeEnd 	= savedInstanceState.getString("fbTimeEnd");
	    	mNotes.setText(savedInstanceState.getString("mNotes"));
	    	mFlagCall.setChecked(savedInstanceState.getBoolean("mFlagCall"));
	    	mFlagBilled.setChecked(savedInstanceState.getBoolean("mFlagBilled"));
    	}
    }
    /**
     * 
     */
    @Override
    protected void onPause() {
        super.onPause();
//        saveState();
    }
    /**
     * 
     */
    @Override
    protected void onResume() {
        super.onResume();
        updateDisplay();
    }
    /**
     * salva i dati della chiamata
     */
    private void saveCall() {
        if (mRowId == null) {
            long id = mDbHelper.createCall(fbCustomer, fbTimeStart, fbTimeEnd, mFlagCall.isChecked(), mNotes.getText().toString(), mFlagBilled.isChecked());
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateCall(mRowId, fbCustomer, fbTimeStart, fbTimeEnd, mFlagCall.isChecked(), mNotes.getText().toString(), mFlagBilled.isChecked());
        }
    }
    /**
     * 
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
		case DLG_ID_DATETIME:
			return createDateTimeDialog();
		default:
		    return null;
	    }
    }
    /**
     * 
     */
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
		case DLG_ID_DATETIME:
			switch (mDateTimeDlgInstance) {
			case DLG_INSTANCE_TIMESTART:
				break;
			case DLG_INSTANCE_TIMEEND:
				break;
			}
			break;
		default:
		    break;
	    }
    }
}